package cn.jcet.module.sys.controller;


import cn.jcet.common.utils.Constast;
import cn.jcet.common.utils.DataGridView;
import cn.jcet.common.utils.ResultObj;
import cn.jcet.common.utils.TreeNode;
import cn.jcet.module.sys.domain.Permission;
import cn.jcet.module.sys.domain.Role;
import cn.jcet.module.sys.service.IPermissionService;
import cn.jcet.module.sys.service.IRoleService;
import cn.jcet.module.sys.vo.RoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鲜磊
 * @since 2019-12-19
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 查询全部
     * @param roleVo
     * @return
     */
    @GetMapping("loadAllRole")
    public DataGridView loadAllRole(RoleVo roleVo){
        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getName()),"name",roleVo.getName());
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        queryWrapper.eq(roleVo.getAvailable()!=null,"available",roleVo.getAvailable());
        queryWrapper.orderByDesc("createtime");
        this.roleService.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 添加
     * @param roleVo
     * @return
     */
    @PostMapping("addRole")
    public ResultObj addRole(RoleVo roleVo){
        try {
            roleVo.setCreatetime(new Date());
            this.roleService.save(roleVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改
     * @param roleVo
     * @return
     */
    @PostMapping("updateRole")
    public ResultObj updateRole(RoleVo roleVo){
        try {
            this.roleService.updateById(roleVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除
     * @param roleVo
     * @return
     */
    @PostMapping("deleteRole")
    public ResultObj deleteRole(RoleVo roleVo){
        try {
            this.roleService.removeById(roleVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


    /**
     * 初始化菜单和角色
     * @param rid
     * @return
     */
    @RequestMapping("initPermissionByRoleId")
    public DataGridView initPermissionByRoleId(Integer roleId){
        /**
         * 查询所以的菜单和权限
         */
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Permission> allPermission = this.permissionService.list(queryWrapper);
        /**
         * 1,根据角色ID查询当前角色拥有的所有的权限或菜单ID
         * 2,根据查询出来的菜单ID查询权限和菜单数据
         */
        List<Integer> currentRolePermission = this.roleService.queryRolePermissionIdsByRid(roleId);

        List<Permission> currentPermission=null;

        if(currentRolePermission.size() >0){
            //如果有id就去查询
            queryWrapper.in("id",currentRolePermission);
            currentPermission = permissionService.list(queryWrapper);
        }else{
            currentPermission = new ArrayList<>();
        }
        //构造List<treeNode>
        List<TreeNode> nodes = new ArrayList<>();
        for (Permission p1:allPermission){
            String checkArr = "0";
            for (Permission p2:currentPermission){
                if(p1.getId() == p2.getId()){
                    checkArr="1";
                    break;
                }
            }
            //判断open为可用
            Boolean spread = (p1.getOpen()==null || p1.getOpen()==1)?true:false;
            nodes.add(new  TreeNode(p1.getId(),p1.getPid(),p1.getTitle(),spread,checkArr));
        }
        return new DataGridView(nodes);
    }

    /**
     * 保存角色和菜单权限之间的关系
     * @param rid
     * @param ids
     * @return
     */
    @PostMapping("saveRolePermission")
    public ResultObj saveRolePermission(Integer rid,Integer [] ids){
        try {
            this.roleService.saveRolePermission(rid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }
}